// pages/menu/menu.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
const util = require('../../utils/util');
import Base64 from '../../utils/Base64.js';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        //传参
        paramObj: {},
        //权限
        authority: {},
        //子菜单列表
        list: [],
        //显示人员管理
        showUser: false,
        //显示设备管理
        showEquipment: false,
        //图片前缀
        prefix: 'http://bangnizu.oss-cn-hangzhou.aliyuncs.com/bangni/images/',
        //简报看板数据
        boardData: {},
        all: 0,
        todayNum: 0,
        recent3: 0,
        recent7: 0,
        recent15: 0,
        repairNum: 0,
        battery: 0,
        //在管总人数
        allUser: 0,
        //人员信息数量
        userNumInfo: null,
        //当前登录用户
        user: null,
        //近几天未使用，默认3，7，15
        daysRange: [3, 7, 15],
        // 显示未完成任务，未审批任务数量
        showNumMenu: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options);
        this.setData({
            user: app.globalData.userInfo,
            authority: app.globalData.authority,
        })

        if (options.paramObj) {
            let paramObj = JSON.parse(options.paramObj);
            console.log('子菜单传参');
            console.log(paramObj);
            this.setData({
              paramObj: paramObj,
              showNumMenu: paramObj.menuNum
            })
            //设置标题
            wx.setNavigationBarTitle({
                title: paramObj.title
            })

          
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        //页面请求写在onShow中，这样从其他页面返回到这里时，数据是最新的
        let paramObj = this.data.paramObj;
        let user = this.data.user;
        //人员管理
        if (paramObj.id == 256) {
            this.setData({
                showUser: true
            })
            //人员简报
            this.personRate();
        }

        //设备管理
        if (paramObj.id == 260) {
            this.setData({
                showEquipment: true
            })

            //客户先查一下是否设置了，其他直接查
            if (user.departObj[0].type == 4) {
                //几天未使用是否在系统设置了（查完再查设备简报）
                this.getSetDay();
            } else {
                //设备简报
                this.getDataCount();
            }
        }
        this.updateMessageCenter();
        //获取子菜单
        this.getMenu();
     
    },

   //统计范围：任务清单，物业工单
    //统计工单管理里面（任务清单，物业工单）未处理的消息条数/未审批的消息条数
    //如果是一级账号或者区域账号登录的，统计未审批的消息条数
    //如果是项目主管账号，统计未完成的消息条数
    getUnFinishTaskAndCleanOrder(){
      return new Promise((resolve, reject) => {
        const departObj = this.data.user.departObj[0]
        let sign = "projectAdministrator"
        if (departObj.isRegion || departObj.level === 1){
           sign = "approver"
        }else if (departObj.isProject){
          sign = "projectAdministrator"
        }
        let param = {
          sign:sign,
          userId:this.data.user.id,
          memberId:departObj.id
        }
        CommonService.getUnFinishTaskAndCleanOrderFunc(param).then(res => {
          if (res.data.data && res.data.data.result != null) {
              let result = res.data.data.result;
              console.log(result);
              // this.setData({
              //   showNumMenu:result
              // })
              resolve(result); // 成功时返回userId
          } else {
            resolve([{
              id:263,
              name: "工单管理",
              children: [{
                      id:385,
                      name: "任务清单",
                      num: 0
                  },
                  {
                      id:277,
                      name: "物业工单",
                      num: 0
                  }
              ],
          }]);
          }
      })

      }).catch((error) => {
        resolve(null);
      });

    },

    //重查消息信息
    async updateMessageCenter(){
      //获取未处理完成的工单和未审核的工单
      const list = await this.getUnFinishTaskAndCleanOrder();
      console.log("list")
      console.log(list)
      let menuNum = []

      for (let i = 0; i < list.length; i++) {
          let menu = list[i];
          if (menu.id === this.data.paramObj.id) {
            console.log(menu.name);
              menuNum = menu.children;
               break;
          }
      }
      this.setData({
        showNumMenu: menuNum
      })
    },

  
    //获取子菜单
    getMenu() {
        let param = {
            isAuth: false,
            className: 'menu',
            data: {
                searchAll: true,
                appId: 3,
                fid: this.data.paramObj.id,
                selectFields: ['id', 'title', 'path', 'ordernum', 'icon', 'perms'],
                nbl: Base64.encode(util.timeFormatDay(new Date())),
                sort: {
                    ordernum: 1
                },
            }
        }

        CommonService.goFindList(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
              
                result.forEach(item => {
              
                    //处理权限
                    if (this.checkKey(item.perms)) {
                        item.showMenu = true;
                    } else {
                        item.showMenu = false;
                    }
                    let has = false
            
                    if (this.data.showNumMenu != null){
                      for (let i = 0; i < this.data.showNumMenu.length; i++) {
                          let menuUnFinishNum = this.data.showNumMenu[i];
                          if (item.title === menuUnFinishNum.name) {
                              //item.showUnFinishNum = true;
                              item.showUnFinishNum = menuUnFinishNum.num > 0;
                              item.unFinishNum = menuUnFinishNum.num > 99 ? "99+" : menuUnFinishNum.num;
                              has = true;
                              break;
                          }
                      }
                        if (!has) {
                          item.showUnFinishNum = false;
                          item.unFinishNum = 0;
                          }
                    }

                });
                this.setData({
                    list: result
                })
            }
        }).catch((error) => {})
    },

    //点击菜单
    goToUrl({
        currentTarget
    }) {
        let detail = currentTarget.dataset.detail;
        let _this = this;

        if (detail.path == '/pages/menu/menu') {
            //如果还有子菜单
            let obj = {
                id: detail.id,
                title: detail.title
            }
            wx.navigateTo({
                url: "/pages/menu/menu?paramObj=" + JSON.stringify(obj)
            })
        } else {
            wx.navigateTo({
                url: detail.path,
                fail: function () {
                    _this.goToNot();
                }
            })
        }
    },
    goToOutInFenceCount() {
        wx.navigateTo({
            url: "/packageA/pages/outInFenceCount/outInFenceCount"
        })
    },
    //跳转到未开发页面
    goToNot() {
        wx.navigateTo({
            url: '/pages/certificate/certificate',
        })
    },

    //菜单根据权限来显示
    checkKey(authority) {
        let currentRole = this.data.authority;
        let authArr = authority.split(':');
        let checkResult = true;

        authArr.forEach((auth, index) => {
            if (index == 0) {
                if (currentRole[auth] && currentRole[auth] != undefined) {
                    if (currentRole[auth] == {}) {
                        checkResult = false;
                    } else {
                        checkResult = currentRole[auth];
                    }
                } else {
                    checkResult = false;
                }
            } else {
                if (checkResult[auth] && checkResult[auth] != undefined) {
                    if (checkResult[auth] == {}) {
                        checkResult = false;
                    } else {
                        checkResult = checkResult[auth];
                    }
                } else {
                    checkResult = false;
                }
            }
        });

        return checkResult;
    },

    //设备数据面板数据
    getDataCount() {
        let arr = this.data.daysRange;
        let param = {
            minRange: arr[0],
            midRange: arr[1],
            maxRange: arr[2]
        }

        CommonService.personCenterCounts(param).then(res => {
            if (res.data.data) {
                let result = res.data.data;
                console.log('设备简报');
                console.log(result);

                this.setData({
                    boardData: result,
                    all: result.all ? result.all.length : 0,
                    todayNum: result.countToday ? result.countToday.length : 0,
                    recent3: result.count3Day ? result.count3Day.length : 0,
                    recent7: result.count7Day ? result.count7Day.length : 0,
                    recent15: result.count15Day ? result.count15Day.length : 0,
                    repairNum: result.countRepair ? result.countRepair.length : 0,
                    battery: result.lowPower ? result.lowPower.length : 0
                })
            }
        }).catch((error) => {})
    },

    //点击总设备
    goToEquipment() {
        wx.navigateTo({
            url: "/pages/equipmentList/equipmentList"
        })
    },

    //点击简报看板
    goToSomeEquipment(e) {
        let key = e.currentTarget.dataset.key;
        let boardData = this.data.boardData;
        let arr = boardData[key];
        let title = e.currentTarget.dataset.title;

        //日志
        if (title) {
            this.loginLog(title);
        }

        //跳转设备列表并传参imei
        if (arr && arr.length) {
            wx.navigateTo({
                url: "/pages/equipmentList/equipmentList?imeiArr=" + JSON.stringify(arr) + "&logTitle=" + title
            })
        }
    },

    //人员简报
    personRate() {
        let today = new Date();
        let todayStr = util.timeFormatDay(new Date());
        let day7 = util.timeFormatDay(util.countPrevDay(today, 6));

        let param = {
            beginDate: day7,
            endDate: todayStr
        }

        CommonService.personnelAttendanceRate(param).then(res => {
            if (res.data.data && res.data.data.result) {
                let result = res.data.data.result;
                console.log('人员简报');
                console.log(result);

                this.setData({
                    //总人数
                    allUser: result.allCount,
                    //其他需要跳转的人员数量（注意字段保持一致）
                    userNumInfo: {
                        //在岗人数
                        attendanceCount: result.attendanceCount && result.attendanceCount.length ? result.attendanceCount : [],
                        //缺岗人数
                        lackOfPostCount: result.lackOfPostCount && result.lackOfPostCount.length ? result.lackOfPostCount : [],
                        //迟到人数
                        lateClockInPersonnelCount: result.lateClockInPersonnelCount && result.lateClockInPersonnelCount.length ? result.lateClockInPersonnelCount : [],
                        //早退人数
                        LeaveEarlyClockInPersonnelCount: result.LeaveEarlyClockInPersonnelCount && result.LeaveEarlyClockInPersonnelCount.length ? result.LeaveEarlyClockInPersonnelCount : [],
                        //进出围栏人数
                        inAndOutFenceCount: result.inAndOutFenceCount && result.inAndOutFenceCount.length ? result.inAndOutFenceCount : [],
                        askForLeave: result.askForLeave && result.askForLeave.length ? result.askForLeave : [],
                    }
                })
            }
        }).catch((error) => {})
    },

    //跳转相应人员
    goToSomeUser({
        currentTarget
    }) {
        let key = currentTarget.dataset.key;
        let info = this.data.userNumInfo;
        let imei = info[key];

        //跳转人员列表并传参imei
        if (imei && imei.length) {
            let obj = {
                imeis: imei
            }
            wx.navigateTo({
                url: "/packageA/pages/userList/userList?paramObj=" + JSON.stringify(obj)
            })
        }
    },

    //跳转设置
    goToSet() {
        let obj = {
            id: 267,
            title: '设置中心'
        }
        wx.navigateTo({
            url: "/pages/menu/menu?paramObj=" + JSON.stringify(obj)
        })
    },

    //跳转人员列表
    goToUserList() {
        wx.navigateTo({
            url: '/packageA/pages/userList/userList'
        })
    },

    //几天未使用是否在系统设置了
    getSetDay() {
        let departO = this.data.user.departObj[0];

        let param = {
            isAuth: true,
            className: 'weChatNewsSend',
            data: {
                searchAll: true,
                'customer.id': departO.companyId,
                selectFields: ['id', 'daysRange', 'customer'],
                nbl: Base64.encode(util.timeFormatDay(new Date()))
            }
        }

        CommonService.goFindList(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result[0];
                console.log('设置几天未使用');
                console.log(result);

                if (result.daysRange && result.daysRange.length) {
                    this.setData({
                        daysRange: result.daysRange
                    })
                }
            }

            //设备简报
            this.getDataCount();

        }).catch((error) => {
            //设备简报
            this.getDataCount();
        })
    },

    //日志
    loginLog(title) {
        let pages = getCurrentPages();
        let lastPage = pages[pages.length - 1];

        let param = {
            logTitle: title,
            function: lastPage.route,
            state: 1
        }

        CommonService.operateLogSave(param).then(res => {}).catch((error) => {})
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})